/*Copyright (C) 2009 Careil Baptiste

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#ifdef WIN32
# include <windows.h>
#else /* WIN32 */
# include <unistd.h>
# include <pthread.h>
#endif /* !WIN32 */

#include "System.h"
#include <stdlib.h>
#include <stdio.h>

///////////////////////////////////////////////////////////
/// Permet d'effacer l'écran
///////////////////////////////////////////////////////////
void DLL_IMPEXP CSLP_ClearScreen()
{
#ifdef WIN32
  system("cls");
#else /* WIN32 */
  system("clear");
#endif /* !WIN32 */
}

///////////////////////////////////////////////////////////
/// Endore le processus pendant une durée donnée
///////////////////////////////////////////////////////////
void DLL_IMPEXP CSLP_Sleep(int ms)
{
#ifdef WIN32
  Sleep((DWORD)(ms));
#else /* WIN32 */
  usleep((unsigned long)(ms * 1000));
#endif /* !WIN32 */
}

///////////////////////////////////////////////////////////
/// Permet la création d'un thread
///////////////////////////////////////////////////////////
int DLL_IMPEXP CSLP_CreateThread(CSLP_THREAD* thread, void* func, void* arg)
{
  int retVal = 0;
#ifdef WIN32
  *thread = CreateThread(NULL, 0, func, arg, 0, NULL);
  if (*thread == NULL)
    {
      retVal = -1;
      perror("Error when creating the thread\n");
    }
#else /* WIN32 */
  if (pthread_create(thread, NULL, func, arg) != 0)
    {
      retVal = -1;
      perror("Error when creating the thread\n");
    }
#endif /* !WIN32 */
  return retVal;
}

///////////////////////////////////////////////////////////
/// Permet d'attendre la fin d'exécution du thread
///////////////////////////////////////////////////////////
void DLL_IMPEXP CSLP_WaitThread(CSLP_THREAD thread)
{
#ifdef WIN32
  WaitForSingleObject(thread, INFINITE);
  CloseHandle(thread);
#else /* WIN32 */
  pthread_join(thread, NULL);
#endif /* !WIN32 */
}

///////////////////////////////////////////////////////////
/// Permet de forcer la fermeture du thread
///////////////////////////////////////////////////////////
void DLL_IMPEXP CSLP_CloseThread(CSLP_THREAD thread)
{
#ifdef WIN32
  TerminateThread(thread, 0);
#else /* WIN32 */
  pthread_cancel(thread);
#endif /* !WIN32 */
}
